<template>
  <el-container class="content">
    <el-aside width="200px" v-loading="showGrouploading" class="left-aside">
      <el-container class="aside-container">
        <el-header class="aside-header">
          <el-input placeholder="输入关键字进行过滤" v-model="groupFilterText" clearable></el-input>
        </el-header>
        <el-main class="nopadding aside-main">
          <el-tree ref="groupRef" class="menu" node-key="id" :data="group" :current-node-key="''"
                   :highlight-current="true" :expand-on-click-node="false"
                   :filter-node-method="groupFilterNode" @node-click="groupClick"></el-tree>
        </el-main>
      </el-container>
    </el-aside>
    <el-container class="main-container">
      <el-header class="main-header">
        <div class="left-panel">
          <el-button type="primary" :icon="plus" @click="showRegister"></el-button>
          <el-button type="danger" plain :icon="deleteIcon" :disabled="selection.length==0"
                     @click="batch_del"></el-button>
          <el-button type="primary" plain :disabled="selection.length===0">分配角色</el-button>
          <el-button type="primary" plain :disabled="selection.length!==1" @click="showRestPassword">密码重置
          </el-button>
        </div>
        <div class="right-panel">
          <div class="right-panel-search">
            <el-input v-model="searchObject.name" placeholder="登录账号 / 姓名" clearable></el-input>
            <el-button type="primary" :icon="searchIcon" @click="search" style="margin-left: 10px;"></el-button>
          </div>
        </div>
      </el-header>
      <el-main class="nopadding main-content">
        <div class="table-container">
          <el-table ref="table" @selection-change="selectionChange" v-loading="loading" :data="pageData.data"
                    @sort-change="changeTableSort"
                    style="width: 100%;font-size: 12px;">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column label="ID" prop="id" width="80" sortable='custom'></el-table-column>
            <el-table-column label="头像" width="80" column-key="filterAvatar"
                             :filters="[{text: '已上传', value: '1'}, {text: '未上传', value: '0'}]">
              <template #default="scope">
                <el-avatar :src="scope.row.avatar" size="small"></el-avatar>
              </template>
            </el-table-column>
            <el-table-column label="登录账号" prop="accountNo" width="180"></el-table-column>
            <el-table-column label="姓名" prop="name" width="150" sortable='custom'></el-table-column>
            <el-table-column label="所属部门" prop="structureName" width="200"></el-table-column>
            <el-table-column label="数据权限" prop="dataScopeName" width="170"></el-table-column>
            <el-table-column label="加入时间" prop="addDate"></el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="160">
              <template #default="scope">
                <el-button-group>
                  <el-button text type="primary" size="small"
                             @click="table_show(scope.row, scope.$index)">查看
                  </el-button>
                  <el-button text type="primary" size="small"
                             @click="table_edit(scope.row, scope.$index)">编辑
                  </el-button>
                  <el-popconfirm title="确定删除吗？" @confirm="deleteData(scope.row)">
                    <template #reference>
                      <el-button text type="danger" size="small">删除</el-button>
                    </template>
                  </el-popconfirm>
                </el-button-group>
              </template>
            </el-table-column>

          </el-table>
        </div>
        <div class="page">
          <el-pagination background :current-page="searchObject.no" :page-sizes="[10, 20, 50, 100]"
                         :page-size="pageData.size" :pager-count="5"
                         layout="total, sizes, prev, pager, next, jumper" :page-count="pageData.totalPage"
                         :total="pageData.total" @size-change="sizeChange" @current-change="pageChange">
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>

  <!-- 删除确认对话框 -->
  <el-dialog title="提示" v-model="dialogVisible" width="30%">
    <span>确认要删除该条数据吗?</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDelete">确 定</el-button>
      </span>
    </template>
  </el-dialog>

  <save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save=false"></save-dialog>
  <el-dialog title="重置密码" v-model="restPasswordVisible" width="30%">
    <el-form :model="form" :rules="rules" label-width="100px" ref="dialogForm"
             label-position="left">
      <el-form-item label="登录密码" prop="restPassword">
        <el-input v-model="form.restPassword" placeholder="请输入登录密码" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="restPasswordVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleRestPassword">确 定</el-button>
        </span>
    </template>
  </el-dialog>

  <el-dialog title="添加账号" v-model="registerVisible" width="30%">
    <el-form :model="registerForm" :rules="registerRules" label-width="100px" ref="registerFormRef"
             label-position="left">
      <el-form-item label="用户账号" prop="username">
        <el-input v-model="registerForm.username" placeholder="请输入账号" clearable></el-input>
      </el-form-item>
      <el-form-item label="登录密码" prop="password">
        <el-input v-model="registerForm.password" placeholder="请输入登录密码" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="registerVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleRegister">确 定</el-button>
        </span>
    </template>
  </el-dialog>


</template>

<script setup>
import {Delete, Plus, Search} from "@element-plus/icons-vue";
import {defineStore} from 'pinia'
import {useDelete} from "@/utils/useDelete";
import {useView} from "@/utils/useView";
import {nextTick, onMounted, ref, watch} from "vue";
import {usePageData} from "@/uses/usePageData.js";
import http from "@/utils/request";
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus'
import {usePage} from "@/utils/usePage.js";

// 定义 Pinia store
const searchStore = defineStore('userStore', {
  state: () => {
    return {
      searchObject: {
        no: 1,
        size: 10,
        sortField: "id",
        sortMethod: "desc",
        name: null,
        structure: null
      }
    }
  }
})

const {searchObject} = searchStore();

// 使用组合式函数
const {
  pageData,
  sizeChange,
  pageChange,
  search,
  changeTableSort,
  loading
} = usePage("userInfo/search", searchObject);

const {dialogVisible, deleteData, handleDelete} = useDelete("/userInfo/delete", search);
const {showView, addView, editView} = useView();

// 响应式数据
const dialog = ref({
  save: false
});
const showGrouploading = ref(false);
const form = ref({
  restPassword: ""
});
const registerForm = ref({
  username: "",
  password: "",
  accountType: "phone"
});
const plus = Plus;
const deleteIcon = Delete;
const searchIcon = Search;
const restPasswordVisible = ref(false);
const registerVisible = ref(false);
const groupFilterText = ref('');
const group = ref([]);
const selection = ref([]);
const saveDialog = ref(null);
const dialogForm = ref(null);
const registerFormRef = ref(null);
const groupRef = ref(null);

const rules = {
  restPassword: [
    {required: true, message: '请输入密码'}
  ]
};

const registerRules = {
  username: [
    {required: true, message: '请输入用户名'}
  ],
  password: [
    {required: true, message: '请输入密码'}
  ]
};

// 监听器
watch(groupFilterText, (val) => {
  groupRef.value?.filter(val);
});

// 方法
const add = () => {
  dialog.value.save = true
  nextTick(() => {
    saveDialog.value.open()
  })
}

const showRestPassword = () => {
  restPasswordVisible.value = true;
}

const showRegister = () => {
  registerVisible.value = true;
}

const handleRestPassword = async () => {
  let password = {};
  password.id = selection.value[0].id;
  password.password = form.value.restPassword;
  await dialogForm.value.validate(async (valid) => {
    if (valid) {
      let res = await http.post("/userInfo/resetPassword", password);
      if (res.code === 200) {
        ElMessage.success("重置密码成功")
        restPasswordVisible.value = false;
      } else {
        ElMessage.error(res.msg)
      }
    } else {
      return false;
    }
  })
}

const handleRegister = async () => {
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      let res = await http.post("/user/register", registerForm.value);
      if (res.code === 200) {
        if (res.data.id) {
          let userForm = {};
          userForm.id = res.data.id;
          if (searchObject.structure) {
            userForm.structure = searchObject.structure;
            userForm.dataScope = "myDepartment";
            await http.post(`/userInfo/update`, userForm);
          }
        }
        ElMessage.success("添加账号成功")
        await search();
        registerVisible.value = false;
      } else {
        ElMessage.error(res.msg)
      }
    } else {
      return false;
    }
  })
}

//编辑
const table_edit = (row) => {
  dialog.value.save = true
  nextTick(() => {
    saveDialog.value.open('update').setData(row)
  })
}

//查看
const table_show = (row) => {
  dialog.value.save = true
  nextTick(() => {
    saveDialog.value.open('show').setData(row)
  })
}

//批量删除
const batch_del = async () => {
  try {
    await ElMessageBox.confirm(`确定删除选中的 ${selection.value.length} 项吗？`, '提示', {
      type: 'warning'
    });

    const loading = ElLoading.service();
    for (const item of selection.value) {
      const res = await http.post(`/userInfo/delete`, item);
      if (res.code !== 200) {
        ElMessage.error(res.msg)
        loading.close();
        return;
      }
    }
    await search();
    loading.close();
    ElMessage.success("操作成功")
  } catch (e) { /* empty */
  }
}

//表格选择后回调事件
const selectionChange = (selectionData) => {
  selection.value = selectionData;
}

//加载树数据
const getGroup = async () => {
  showGrouploading.value = true;
  let res = await http.post(`/structure/list`, {depth: 1, fetch: 1});
  showGrouploading.value = false;
  if (res.code !== 200 || res.data === null) {
    return;
  }
  const allNode = {id: '', label: '所有'};
  res.data.unshift(allNode);
  group.value = res.data;
}

//树过滤
const groupFilterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
}

//树点击事件
const groupClick = (data) => {
  searchObject.structure = data.id;
  search();
}

//本地更新数据
const handleSuccess = (data, mode) => {
  if (mode === 'create') {
    data.id = new Date().getTime()
    search();
  } else if (mode === 'update') {
    search();
  }
}

// 生命周期
onMounted(() => {
  getGroup()
});
</script>

<style>
.content {
  background-color: #fff;
  padding: 15px 5px;
  height: 100%;
  display: flex;
  overflow: hidden;
}

/* 左侧边栏样式 */
.left-aside {
  height: 100%;
  border-right: 1px solid var(--el-border-color-light);
  display: flex;
  flex-direction: column;
}

.aside-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.aside-header {
  background: #fff;
  border-bottom: 1px solid var(--el-border-color-light);
  padding: 13px 15px;
  height: 60px;
  flex-shrink: 0;
}

.aside-main {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  min-height: 0;
}

/* 主容器样式 */
.main-container {
  height: 100%;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.main-header {
  background: #fff;
  border-bottom: 1px solid var(--el-border-color-light);
  padding: 13px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  flex-shrink: 0;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.table-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: auto;
  min-height: 0;
}

.page {
  padding: 15px;
  border-top: 1px solid var(--el-border-color-light);
  background: #fff;
  flex-shrink: 0;
}

.right-panel-search {
  display: flex;
  align-items: center;
}

/* 确保树组件可以正常滚动 */
.menu {
  height: 100%;
  overflow-y: auto;
}

/* 移除默认的padding */
.nopadding {
  padding: 0 !important;
}
</style>
